package com.content.model.Communication
{
	import com.library.core.IDisposable;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import org.aswing.JOptionPane;
	import org.aswing.geom.IntDimension;
	
	public class WebAPILoader extends EventDispatcher implements IDisposable
	{
		protected var _handler:Function;
		private var _url:String;
		
		public function WebAPILoader(handler:Function = null)
		{
			super();
			_handler = handler;
		}
		
		public function Load(request:URLRequest):void{
			_url = request.url;
			var urlLoader:URLLoader = new URLLoader(request);
			urlLoader.addEventListener(Event.COMPLETE, OnLoadComplete);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR, OnLoadError);
			urlLoader.load(request);
		}
		
		/* Event Handler
		*----------------------------------------------------------------------------*/
		protected function OnLoadComplete(evt:Event):void{
			URLLoader(evt.target).removeEventListener(Event.COMPLETE, OnLoadComplete);
			URLLoader(evt.target).removeEventListener(IOErrorEvent.IO_ERROR, OnLoadError);
			if (_handler != null){
				var result:XML = new XML( evt.target.data );
				_handler(result);
			}
		}
		
		private function OnLoadError(evt:IOErrorEvent):void{
			URLLoader(evt.target).removeEventListener(Event.COMPLETE, OnLoadComplete);
			URLLoader(evt.target).removeEventListener(IOErrorEvent.IO_ERROR, OnLoadError);
			
			var jop:JOptionPane = JOptionPane.showMessageDialog(
				"提示",
				"网络连接错误，无法从下面地址返回数据:\n" + _url,
				null,
				null, true, null,
				JOptionPane.OK);
			jop.getFrame().setDefaultButton(jop.getOkButton());
			jop.getFrame().setSize(new IntDimension(400, 135));
			
		}
		
		public function Dispose():void	{		_handler = null;		}
	}
}